package com.gzhryc.shared_device.oem.micro.queue.handlers.profit;

import com.gzhryc.common.event.AbsDelayHandler;
import com.gzhryc.common.logging.Logger;
import com.gzhryc.shared_device.oem.code.profit.dao.db.BusinessOrder;
import com.gzhryc.shared_device.oem.code.profit.dao.db.BusinessOrderUserProfit;
import com.gzhryc.shared_device.oem.code.profit.event.UserProfitCancelEvent;
import com.gzhryc.shared_device.oem.code.profit.service.BusinessOrderService;
import com.gzhryc.shared_device.oem.code.profit.service.BusinessOrderUserProfitService;
import com.gzhryc.shared_device.oem.code.statistics.services.ProjectProfitDayStatisticsService;
import com.gzhryc.shared_device.oem.code.statistics.services.UserProfitDayStatisticsService;
import com.gzhryc.shared_device.oem.code.user.ERoleType;

import java.util.List;

public class UserProfitCancelEventHandler extends AbsDelayHandler<UserProfitCancelEvent> {

    static Logger log = Logger.getLogger(UserProfitCancelEventHandler.class);

    @Override
    public boolean execute(UserProfitCancelEvent event) {
        try{
            BusinessOrder businessOrder = BusinessOrderService.self(event.getCreateDate()).getByTradeNo(event.getTradeNo());
            if(businessOrder != null) {
                if (BusinessOrderUserProfitService.self(event.getCreateDate()).revokeIncome(businessOrder, event.getOperateInfo())) {
                    //获取最新数据
                    businessOrder = BusinessOrderService.self(event.getCreateDate()).getByTradeNo(event.getTradeNo());
                    //统计处理
                    List<BusinessOrderUserProfit> userProfitList = BusinessOrderUserProfitService.self(businessOrder.getCreateDate()).findByTradeNo(businessOrder.getTradeNo());
                    if(userProfitList != null && userProfitList.size() > 0){
                        for(BusinessOrderUserProfit userProfit : userProfitList){
                            if(ERoleType.Sys.index().equals(userProfit.getRoleType())){
                                ProjectProfitDayStatisticsService.self().addOneRefundData(businessOrder.getDivideDate()
                                        ,userProfit.getMoney(),businessOrder.getCancelDate());
                            }else{
                                UserProfitDayStatisticsService.self().addOneRefundData(userProfit.getUserId(),userProfit.getName(),userProfit.getPhone()
                                        ,businessOrder.getDivideDate(),userProfit.getMoney(),businessOrder.getCancelDate());
                            }
                        }
                    }
                }
            }
        }catch (Exception e){
            log.error(e.getMessage(),e);
        }
        return true;
    }
}
